<template>
  <div class="discussion-page">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="navbar-container">
        <div class="navbar-left">
          <router-link to="/" class="logo-link">
            <svg class="logo-icon" viewBox="0 0 48 48" width="36" height="36" fill="none" xmlns="http://www.w3.org/2000/svg">
              <rect width="48" height="48" rx="12" fill="url(#logoGradient)"/>
              <path d="M12 32V16L18 24L24 16L30 24L36 16V32" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
              <circle cx="18" cy="25" r="1.5" fill="white" opacity="0.8"/>
              <circle cx="30" cy="25" r="1.5" fill="white" opacity="0.8"/>
              <defs>
                <linearGradient id="logoGradient" x1="0" y1="0" x2="48" y2="48" gradientUnits="userSpaceOnUse">
                  <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
                  <stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
                </linearGradient>
              </defs>
            </svg>
            <span class="logo">M-Learning</span>
          </router-link>
        </div>
        
        <div class="navbar-center">
          <router-link to="/home" class="nav-link">首页</router-link>
          <router-link to="/discussion" class="nav-link active">帖子</router-link>
        </div>
        
        <div class="navbar-right">
          <div class="navbar-icon notification-icon" @click="openMessageList" title="私信">
            <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
              <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
            </svg>
            <span v-if="unreadCount > 0" class="notification-badge">{{ unreadCount }}</span>
          </div>
          
          <div class="user-dropdown" @mouseenter="showUserMenu = true" @mouseleave="showUserMenu = false">
            <div class="user-info-trigger">
              <div class="user-avatar" @click="handleAvatarClick" style="cursor: pointer;" title="点击更换头像">
                <img 
                  v-if="userInfo && userInfo.avatar" 
                  :src="getAvatarUrl(userInfo.avatar)" 
                  alt="头像"
                />
                <span v-else class="avatar-placeholder">
                  {{ userInfo?.nickname?.charAt(0) || userInfo?.phone?.charAt(userInfo.phone.length - 1) || '未' }}
                </span>
              </div>
              <span class="user-display-name">{{ userInfo?.nickname || userInfo?.phone || '未登录' }}</span>
            </div>
            
            <transition name="fade">
              <div v-if="showUserMenu" class="dropdown-menu">
                <div class="user-info-box">
                  <div class="user-name">{{ userInfo?.nickname || userInfo?.phone || '未登录' }}</div>
                  <div class="user-role">{{ userRoleText }}</div>
                </div>
                <div class="dropdown-divider"></div>
                <router-link to="/profile" class="dropdown-item">
                  <span class="icon">👤</span>
                  个人资料
                </router-link>
                <router-link to="/my-learning" class="dropdown-item">
                  <span class="icon">📚</span>
                  我的学习
                </router-link>
                <router-link to="/my-posts" class="dropdown-item">
                  <span class="icon">💬</span>
                  我的帖子
                </router-link>
                <div class="dropdown-divider"></div>
                <a href="#" class="dropdown-item" @click.prevent="handleLogout">
                  <span class="icon">🚪</span>
                  退出登录
                </a>
              </div>
            </transition>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <div class="content-container">
        <!-- 顶部操作栏 -->
        <div class="discussion-header">
          <h1 class="page-title">讨论区</h1>
          <button class="publish-btn" @click="showPublishDialog = true">
            <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
              <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
            </svg>
            发布帖子
          </button>
        </div>

        <!-- 搜索框 -->
        <div class="search-container">
          <div class="search-wrapper">
            <svg class="search-icon" viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
              <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
            </svg>
            <input 
              v-model="searchKeyword"
              type="text"
              class="search-input"
              placeholder="搜索帖子..."
              @keyup.enter="handleSearchSubmit"
            />
            <!-- 搜索中状态 -->
            <div v-if="searching" class="searching-spinner">
              <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" class="spin">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-3.31 0-6 2.69-6 6h2c0-2.21 1.79-4 4-4V6z"/>
              </svg>
            </div>
            <button 
              v-else-if="searchKeyword"
              class="clear-btn"
              @click="clearSearch"
              title="清除"
            >
              <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor">
                <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
              </svg>
            </button>
          </div>
          
          <div v-if="searchKeyword && discussions.length > 0" class="search-result-info">
            找到 <strong>{{ total }}</strong> 个相关帖子
          </div>
          <div v-if="searchKeyword && discussions.length === 0 && !loading" class="search-no-result">
            <svg viewBox="0 0 24 24" width="48" height="48" fill="currentColor" opacity="0.3">
              <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
            </svg>
            <p>未找到相关帖子</p>
            <button class="btn-clear-search" @click="clearSearch">清除搜索</button>
          </div>
        </div>

        <!-- 标签筛选 -->
        <div class="tags-filter">
          <button 
            :class="['tag-btn', { active: selectedTag === '' }]" 
            @click="selectTag('')"
          >
            全部
          </button>
          <button 
            v-for="tag in hotTags" 
            :key="tag.id"
            :class="['tag-btn', { active: selectedTag === tag.name }]"
            @click="selectTag(tag.name)"
          >
            {{ tag.name }}
          </button>
        </div>

        <!-- 排序和筛选 -->
        <div class="filter-bar">
          <div class="sort-tabs">
            <button 
              :class="['sort-tab', { active: sortType === 'hot' }]"
              @click="changeSortType('hot')"
            >
              🔥 热门
            </button>
            <button 
              :class="['sort-tab', { active: sortType === 'latest' }]"
              @click="changeSortType('latest')"
            >
              🕐 最新
            </button>
            <button 
              :class="['sort-tab', { active: sortType === 'unanswered' }]"
              @click="changeSortType('unanswered')"
            >
              ❓ 未回答
            </button>
          </div>
        </div>

        <!-- 讨论列表 -->
        <div v-if="loading" class="loading">加载中...</div>
        <div v-else-if="discussions.length === 0" class="empty">
          <svg viewBox="0 0 24 24" width="64" height="64" fill="#ccc">
            <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/>
          </svg>
          <p>暂无讨论</p>
        </div>
        <div v-else class="discussion-list">
          <div 
            v-for="item in discussions" 
            :key="item.id"
            class="discussion-item"
            @click="goToDetail(item.id)"
          >
            <!-- 用户头像 -->
            <div 
              class="item-avatar"
              @mouseenter.stop="handleUserHover(item.author.id, $event)"
              @mouseleave.stop="handleUserLeave"
              @click.stop
            >
              <img 
                v-if="item.author.avatar" 
                :src="getAvatarUrl(item.author.avatar)" 
                :alt="item.author.nickname"
              />
              <span v-else class="avatar-text">
                {{ item.author.nickname?.charAt(0) || 'U' }}
              </span>
            </div>

            <!-- 讨论内容 -->
            <div class="item-content">
              <h3 class="item-title">{{ item.title }}</h3>
              <div class="item-preview" v-html="renderPreview(item.preview || item.content)"></div>
              <div class="item-meta">
                <span class="author-name">{{ item.author.nickname }}</span>
                <span class="separator">·</span>
                <span class="time">{{ formatTime(item.createdAt) }}</span>
                <span class="separator">·</span>
                <span class="location">{{ item.author.location || userInfo?.location || '中国' }}</span>
                <div class="tags">
                  <span v-for="tag in item.tags" :key="tag" class="tag">{{ tag }}</span>
                </div>
              </div>
            </div>

            <!-- 统计信息 -->
            <div class="item-stats">
              <div class="stat-item">
                <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                  <path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-2z"/>
                </svg>
                <span>{{ item.likes }}</span>
              </div>
              <div class="stat-item">
                <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                  <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
                </svg>
                <span>{{ item.comments }}</span>
              </div>
              <div class="stat-item">
                <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                  <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                </svg>
                <span>{{ item.favorites }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="totalPages > 1" class="pagination">
          <button 
            class="page-btn" 
            :disabled="currentPage === 1"
            @click="changePage(currentPage - 1)"
          >
            上一页
          </button>
          <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
          <button 
            class="page-btn"
            :disabled="currentPage === totalPages"
            @click="changePage(currentPage + 1)"
          >
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 发布讨论弹窗 -->
    <PublishDiscussion 
      v-if="showPublishDialog" 
      @close="showPublishDialog = false"
      @submit="handlePublish"
    />

    <!-- 用户卡片悬停 -->
    <div 
      v-if="hoveredUser"
      class="user-card-container"
      :style="{
        position: 'absolute',
        top: hoveredUser.position.top + 'px',
        left: hoveredUser.position.left + 'px',
        zIndex: 1000
      }"
      @mouseenter="handleCardHover"
      @mouseleave="handleCardLeave"
    >
      <UserCard 
        :userId="hoverUserId"
        @message="handleMessage"
      />
    </div>

    <!-- 私信列表 -->
    <MessageList
      v-if="showMessageList"
      @close="closeMessageList"
      @openChat="openMessageDialog"
    />

    <!-- 私信对话 -->
    <MessageDialog
      v-if="showMessageDialog"
      :targetUser="messageTargetUser"
      @close="closeMessageDialog"
      @back="backToMessageList"
    />

    <!-- 隐藏的头像上传input -->
    <input 
      type="file" 
      ref="avatarInput" 
      accept="image/*" 
      style="display: none"
      @change="handleAvatarChange"
    />

    <!-- Toast提示 -->
    <Toast ref="toastRef" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { getDiscussionList, getHotTags } from '../api/discussion'
import { getAvatarUrl } from '../utils/url'
import { uploadAvatar } from '../api/user'
import PublishDiscussion from '../components/PublishDiscussion.vue'
import { renderMathInHTML } from '../utils/renderMath'
import UserCard from '../components/UserCard.vue'
import MessageList from '../components/MessageList.vue'
import MessageDialog from '../components/MessageDialog.vue'
import Toast from '../components/Toast.vue'
import { getUnreadCount } from '../api/message'

const router = useRouter()
const userStore = useUserStore()

const userInfo = computed(() => userStore.userInfo)
const userRoleText = computed(() => {
  if (!userInfo.value) return '未登录'
  console.log('当前用户信息:', userInfo.value)
  console.log('用户角色字段:', userInfo.value.role)
  return userInfo.value.role === 'admin' ? '管理员' : '普通用户'
})
const showUserMenu = ref(false)
const unreadCount = ref(0)
const avatarInput = ref(null)
const toastRef = ref(null)

// 用户卡片悬停
const hoveredUser = ref(null)
const hoverUserId = ref(null)
let hoverTimer = null

// 私信对话
const showMessageList = ref(false)
const showMessageDialog = ref(false)
const messageTargetUser = ref(null)

// 讨论列表相关
const discussions = ref([])
const loading = ref(false)
const searching = ref(false) // 搜索中状态
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0) // 总数
const totalPages = ref(1)
const sortType = ref('hot') // hot, latest, unanswered
const selectedTag = ref('')
const searchKeyword = ref('') // 搜索关键词
const hotTags = ref([])

// 发布弹窗
const showPublishDialog = ref(false)

onMounted(async () => {
  // 检查登录状态
  console.log('Discussion mounted - Token:', userStore.token)
  console.log('Discussion mounted - UserInfo:', userStore.userInfo)
  
  if (!userStore.token || !userStore.userInfo) {
    console.warn('用户未登录，跳转到登录页')
    router.push('/login')
    return
  }
  
  // 初始化 WebSocket 连接
  try {
    const { initWebSocket } = await import('../utils/websocket')
    initWebSocket(userStore.token)
  } catch (error) {
    console.error('WebSocket 初始化失败:', error)
  }
  
  loadDiscussions()
  loadHotTags()
  loadUnreadCount()
})

// 加载未读消息数量
async function loadUnreadCount() {
  try {
    const res = await getUnreadCount()
    if (res.code === 200) {
      unreadCount.value = res.data.count || 0
    }
  } catch (error) {
    console.error('获取未读消息数失败:', error)
    // 使用模拟数据
    unreadCount.value = 3
  }
}

async function loadDiscussions() {
  loading.value = true
  searching.value = true
  try {
    const res = await getDiscussionList({
      page: currentPage.value,
      pageSize: pageSize.value,
      sort: sortType.value,
      tag: selectedTag.value,
      keyword: searchKeyword.value // 添加搜索关键词
    })
    
    if (res.code === 200) {
      discussions.value = res.data.list
      total.value = res.data.total
      totalPages.value = Math.ceil(res.data.total / pageSize.value)
    }
  } catch (error) {
    console.error('加载讨论列表失败:', error)
    // 使用模拟数据
    setMockData()
  } finally {
    loading.value = false
    searching.value = false
  }
}

async function loadHotTags() {
  try {
    const res = await getHotTags()
    if (res.code === 200) {
      hotTags.value = res.data
    }
  } catch (error) {
    console.error('加载热门标签失败:', error)
    // 模拟数据
    hotTags.value = [
      { id: 1, name: '极限' },
      { id: 2, name: '三角函数' },
      { id: 3, name: '中级' },
      { id: 4, name: '代数' },
      { id: 5, name: '几何' }
    ]
  }
}

function setMockData() {
  discussions.value = [
    {
      id: 1,
      title: '这一次，我们一起赢回来。🏆',
      preview: '讨论如何提升数学学习效率和方法...',
      author: {
        nickname: 'Kita3',
        avatar: '',
        location: '福建'
      },
      tags: ['极限', '三角函数'],
      likes: 100,
      comments: 46,
      favorites: 121,
      createdAt: '2025-09-03T10:30:00'
    },
    {
      id: 2,
      title: '求函数的极限值详解',
      preview: '计算当x趋向于0时，sin(x)/x的极限值...',
      author: {
        nickname: 'undercat',
        avatar: '',
        location: '江苏'
      },
      tags: ['极限', '中级'],
      likes: 73,
      comments: 28,
      favorites: 45,
      createdAt: '2025-10-20T14:20:00'
    },
    {
      id: 3,
      title: '懂得成为2000分 🏅',
      preview: '分享我的数学学习经验和刷题心得...',
      author: {
        nickname: 'MathMaster',
        avatar: '',
        location: '江苏'
      },
      tags: ['学习方法', '经验分享'],
      likes: 156,
      comments: 89,
      favorites: 203,
      createdAt: '2025-09-05T16:45:00'
    }
  ]
  totalPages.value = 3
}

function selectTag(tag) {
  selectedTag.value = tag
  currentPage.value = 1
  loadDiscussions()
}

function changeSortType(type) {
  sortType.value = type
  currentPage.value = 1
  loadDiscussions()
}

function changePage(page) {
  currentPage.value = page
  loadDiscussions()
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 搜索功能
let searchTimer = null

// 防抖搜索
function debouncedSearch() {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    currentPage.value = 1
    loadDiscussions()
  }, 300) // 300ms后执行搜索（实时搜索）
}

// 监听搜索关键词变化（实时搜索）
watch(searchKeyword, (newVal) => {
  debouncedSearch()
})

// 手动搜索（回车键）
function handleSearchSubmit() {
  clearTimeout(searchTimer)
  currentPage.value = 1
  loadDiscussions()
}

function clearSearch() {
  searchKeyword.value = ''
  currentPage.value = 1
  loadDiscussions()
}

function goToDetail(id) {
  router.push(`/discussion/${id}`)
}

function handlePublish(data) {
  showPublishDialog.value = false
  // 刷新列表
  currentPage.value = 1
  loadDiscussions()
}

function handleSearch() {
  alert('搜索功能开发中...')
}

// 用户卡片悬停处理
function handleUserHover(userId, event) {
  clearTimeout(hoverTimer)
  hoverTimer = setTimeout(() => {
    hoverUserId.value = userId
    const rect = event.target.closest('.item-avatar').getBoundingClientRect()
    hoveredUser.value = {
      userId,
      position: {
        top: rect.bottom + window.scrollY + 8,
        left: rect.left + window.scrollX
      }
    }
  }, 300) // 300ms后显示
}

function handleUserLeave() {
  clearTimeout(hoverTimer)
  hoverTimer = setTimeout(() => {
    hoveredUser.value = null
    hoverUserId.value = null
  }, 200)
}

function handleCardHover() {
  clearTimeout(hoverTimer)
}

function handleCardLeave() {
  hoveredUser.value = null
  hoverUserId.value = null
}

// 私信处理
function handleMessage(user) {
  hoveredUser.value = null
  messageTargetUser.value = user
  showMessageDialog.value = true
}

function openMessageList() {
  showMessageList.value = true
}

function closeMessageList() {
  showMessageList.value = false
}

function openMessageDialog(user) {
  showMessageList.value = false
  messageTargetUser.value = user
  showMessageDialog.value = true
}

function closeMessageDialog() {
  showMessageDialog.value = false
  messageTargetUser.value = null
  // 刷新未读消息数
  loadUnreadCount()
}

function backToMessageList() {
  showMessageDialog.value = false
  showMessageList.value = true
}

// 头像上传功能
function handleAvatarClick() {
  avatarInput.value.click()
}

async function handleAvatarChange(event) {
  const file = event.target.files[0]
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    toastRef.value?.show({
      title: '上传失败',
      message: '请选择图片文件',
      type: 'error'
    })
    return
  }

  // 验证文件大小 (2MB)
  if (file.size > 2 * 1024 * 1024) {
    toastRef.value?.show({
      title: '上传失败',
      message: '图片大小不能超过2MB',
      type: 'error'
    })
    return
  }

  try {
    const formData = new FormData()
    formData.append('avatar', file)

    const { data } = await uploadAvatar(formData)
    
    // 更新用户信息
    userStore.setUserInfo({
      ...userInfo.value,
      avatar: data.avatar
    })

    toastRef.value?.show({
      title: '上传成功',
      message: '头像已更新',
      type: 'success'
    })
  } catch (error) {
    console.error('上传头像失败:', error)
    toastRef.value?.show({
      title: '上传失败',
      message: error.message || '请稍后重试',
      type: 'error'
    })
  } finally {
    // 清空input值，允许重复上传同一文件
    event.target.value = ''
  }
}

async function handleLogout() {
  // 关闭 WebSocket 连接
  const { closeWebSocket } = await import('../utils/websocket')
  closeWebSocket()
  
  userStore.logout()
  router.push('/login')
}

function formatTime(dateStr) {
  const date = new Date(dateStr)
  const now = new Date()
  const diff = now - date
  
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return date.toLocaleDateString('zh-CN')
}

function renderPreview(preview) {
  if (!preview) return ''
  // 渲染预览中的数学公式
  return renderMathInHTML(preview)
}
</script>

<style lang="scss" scoped>
.discussion-page {
  min-height: 100vh;
  background: #f5f7fa;
}

// 顶部导航栏样式（复用）
.top-navbar {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 24px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar-left {
  .logo-link {
    text-decoration: none;
    display: flex;
    align-items: center;
    gap: 12px;
    transition: transform 0.3s;
    
    &:hover {
      transform: translateY(-2px);
      
      .logo-icon {
        transform: rotate(5deg) scale(1.05);
      }
    }
    
    .logo-icon {
      display: block;
      transition: transform 0.3s;
      filter: drop-shadow(0 2px 8px rgba(102, 126, 234, 0.3));
    }
    
    .logo {
      font-size: 24px;
      font-weight: bold;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      letter-spacing: 0.5px;
    }
  }
}

.navbar-center {
  display: flex;
  gap: 32px;
  
  .nav-link {
    color: #666;
    text-decoration: none;
    font-size: 15px;
    transition: color 0.2s;
    
    &:hover, &.active {
      color: #667eea;
    }
  }
}

.navbar-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.navbar-icon {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
  border-radius: 50%;
  transition: all 0.3s;
  position: relative;
  
  &:hover {
    background: #f5f5f5;
    color: #333;
  }
}

.notification-icon {
  position: relative;
  
  .notification-badge {
    position: absolute;
    top: 2px;
    right: 2px;
    min-width: 16px;
    height: 16px;
    padding: 0 4px;
    background: #ff4757;
    color: white;
    font-size: 10px;
    font-weight: bold;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.user-dropdown {
  position: relative;
  
  .user-info-trigger {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    padding: 4px 12px 4px 4px;
    border-radius: 24px;
    transition: background 0.3s;
    
    &:hover {
      background: #f5f5f5;
    }
  }
  
  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    font-size: 16px;
    font-weight: bold;
    overflow: hidden;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  .user-display-name {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    white-space: nowrap;
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.dropdown-menu {
  position: absolute;
  top: 50px;
  right: 0;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  min-width: 200px;
  overflow: hidden;
  
  .user-info-box {
    padding: 16px;
    background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%);
    
    .user-name {
      font-size: 16px;
      font-weight: bold;
      color: #333;
      margin-bottom: 4px;
    }
    
    .user-id {
      font-size: 12px;
      color: #999;
    }
    
    .user-role {
      font-size: 12px;
      color: #667eea;
      margin-top: 6px;
      padding: 2px 8px;
      background: rgba(102, 126, 234, 0.1);
      border-radius: 10px;
      display: inline-block;
      font-weight: 500;
    }
  }
  
  .dropdown-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 12px 16px;
    color: #666;
    text-decoration: none;
    transition: background 0.2s;
    
    &:hover {
      background: #f5f7fa;
    }
    
    .icon {
      font-size: 18px;
    }
  }
  
  .dropdown-divider {
    height: 1px;
    background: #eee;
    margin: 4px 0;
  }
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

// 主内容区
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 32px 24px;
}

.content-container {
  background: white;
  border-radius: 12px;
  overflow: hidden;
}

.discussion-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px 32px;
  border-bottom: 1px solid #eee;
  
  .page-title {
    font-size: 28px;
    font-weight: bold;
    color: #333;
    margin: 0;
  }
  
  .publish-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 24px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 15px;
    font-weight: 500;
    cursor: pointer;
    transition: transform 0.2s, box-shadow 0.2s;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }
    
    svg {
      display: block;
    }
  }
}

.search-container {
  padding: 16px 32px;
  border-bottom: 1px solid #eee;
  
  .search-wrapper {
    display: flex;
    align-items: center;
    gap: 10px;
    max-width: 600px;
    padding: 8px 16px;
    background: white;
    border: 1px solid #e1e4e8;
    border-radius: 6px;
    transition: all 0.2s;
    
    &:hover {
      border-color: #c1c7cd;
    }
    
    &:focus-within {
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
    
    .search-icon {
      flex-shrink: 0;
      color: #8c959f;
    }
    
    .search-input {
      flex: 1;
      border: none;
      background: transparent;
      font-size: 14px;
      outline: none;
      color: #24292f;
      min-width: 0;
      
      &::placeholder {
        color: #8c959f;
      }
    }
    
    .searching-spinner {
      flex-shrink: 0;
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #667eea;
      
      .spin {
        animation: spin 1s linear infinite;
      }
    }
    
    .clear-btn {
      flex-shrink: 0;
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: transparent;
      border: none;
      border-radius: 3px;
      cursor: pointer;
      color: #8c959f;
      transition: all 0.15s;
      
      &:hover {
        background: #f3f4f6;
        color: #24292f;
      }
    }
  }
  
  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
  
  .search-result-info {
    margin-top: 12px;
    font-size: 13px;
    color: #57606a;
    
    strong {
      color: #24292f;
      font-weight: 600;
    }
  }
  
  .search-no-result {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    
    svg {
      margin-bottom: 16px;
    }
    
    p {
      font-size: 16px;
      color: #999;
      margin: 0 0 20px 0;
    }
    
    .btn-clear-search {
      padding: 6px 16px;
      background: white;
      color: #24292f;
      border: 1px solid #d0d7de;
      border-radius: 6px;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.15s;
      
      &:hover {
        background: #f6f8fa;
        border-color: #c1c7cd;
      }
    }
  }
}

.tags-filter {
  display: flex;
  gap: 12px;
  padding: 20px 32px;
  border-bottom: 1px solid #eee;
  overflow-x: auto;
  
  &::-webkit-scrollbar {
    height: 4px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #ddd;
    border-radius: 2px;
  }
  
  .tag-btn {
    padding: 6px 16px;
    background: #f5f7fa;
    color: #666;
    border: 1px solid transparent;
    border-radius: 20px;
    font-size: 14px;
    white-space: nowrap;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover {
      background: #e8ecf1;
    }
    
    &.active {
      background: #ede7f6;
      color: #667eea;
      border-color: #667eea;
    }
  }
}

.filter-bar {
  padding: 16px 32px;
  border-bottom: 1px solid #eee;
  
  .sort-tabs {
    display: flex;
    gap: 24px;
    
    .sort-tab {
      padding: 8px 0;
      background: none;
      border: none;
      border-bottom: 2px solid transparent;
      color: #666;
      font-size: 15px;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        color: #333;
      }
      
      &.active {
        color: #667eea;
        border-bottom-color: #667eea;
        font-weight: 500;
      }
    }
  }
}

.loading, .empty {
  padding: 80px 32px;
  text-align: center;
  color: #999;
  font-size: 16px;
}

.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.discussion-list {
  .discussion-item {
    display: flex;
    gap: 16px;
    padding: 24px 32px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: background 0.2s;
    
    &:hover {
      background: #fafbfc;
    }
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .item-avatar {
    flex-shrink: 0;
    width: 48px;
    height: 48px;
    border-radius: 50%;
    overflow: hidden;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    cursor: pointer;
    transition: transform 0.2s;
    
    &:hover {
      transform: scale(1.05);
    }
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .avatar-text {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 20px;
      font-weight: bold;
    }
  }
  
  .item-content {
    flex: 1;
    min-width: 0;
    
    .item-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
      margin: 0 0 8px 0;
      line-height: 1.4;
    }
    
    .item-preview {
      font-size: 14px;
      color: #666;
      margin-bottom: 12px;
      max-height: 120px;  // 限制最大高度
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 3;  // 最多3行
      -webkit-box-orient: vertical;
      
      // 数学公式样式
      :deep(.math-display) {
        display: inline;
        margin: 0 4px;
        
        .katex-display {
          display: inline;
          margin: 0;
        }
        
        .katex {
          font-size: 0.9em;
        }
      }
      
      :deep(.math-inline) {
        display: inline;
        margin: 0 2px;
        
        .katex {
          font-size: 0.9em;
        }
      }
      
      :deep(.math-error) {
        display: none; // 列表页隐藏错误提示
      }
      
      // 图片样式 - 小缩略图
      :deep(.content-image),
      :deep(.discussion-image),
      :deep(img) {
        display: inline-block;
        max-width: 120px;  // 小缩略图
        max-height: 80px;
        width: auto;
        height: auto;
        margin: 4px 8px 4px 0;
        border-radius: 4px;
        object-fit: cover;
        vertical-align: middle;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
        cursor: pointer;
        transition: transform 0.2s;
        
        &:hover {
          transform: scale(1.05);
        }
      }
    }
    
    .item-meta {
      display: flex;
      align-items: center;
      gap: 8px;
      flex-wrap: wrap;
      font-size: 13px;
      color: #999;
      
      .author-name {
        color: #666;
        font-weight: 500;
      }
      
      .separator {
        color: #ddd;
      }
      
      .tags {
        display: flex;
        gap: 8px;
        margin-left: 8px;
        
        .tag {
          padding: 2px 10px;
          background: #f5f7fa;
          color: #667eea;
          border-radius: 4px;
          font-size: 12px;
        }
      }
    }
  }
  
  .item-stats {
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: flex-end;
    justify-content: center;
    flex-shrink: 0;
    
    .stat-item {
      display: flex;
      align-items: center;
      gap: 6px;
      color: #999;
      font-size: 14px;
      
      svg {
        display: block;
      }
    }
  }
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  padding: 24px 32px;
  border-top: 1px solid #eee;
  
  .page-btn {
    padding: 8px 16px;
    background: #f5f7fa;
    color: #666;
    border: none;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s;
    
    &:hover:not(:disabled) {
      background: #667eea;
      color: white;
    }
    
    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
  
  .page-info {
    font-size: 14px;
    color: #666;
  }
}

@media (max-width: 768px) {
  .discussion-item {
    flex-direction: column;
    
    .item-stats {
      flex-direction: row !important;
      justify-content: flex-start !important;
    }
  }
  
  .discussion-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}
</style>

